<?php

class Service_grc extends MY_Service
{
    public function __construct()
    {
        parent::__construct();
        $this->load->library('HttpUtil');
        $this->load->config('common/grc_api');
    }

    public function check($url)
    {
        $grcList = ['tencent_security', 'wechat_security', '360_security', 'douyin_security', 'xiaomi_security', 'google_security', 'huawei_security'];
        foreach ($grcList as $grc) {
            $result = $this->_getResult($url, $grc);
            list($res['flag'][$grc], $res['msg'][$grc]) = $this->_makeResult($grc, $result);
        }

        $flag = true;
        foreach ($res['flag'] as $item) {
            $flag = $flag && $item;
        }

        $msg = "";
        foreach ($res['msg'] as $grc => $item) {
            if (!$res['flag'][$grc] || $grc == 'tencent_security') {
                $msg = $msg . "$grc:$item,";
            }
        }
        $msg = trim($msg, ',');
        return [$flag, $msg];
    }

    private function _getResult($url, $grc)
    {
        $site = $this->config->item($grc);
        $site['url'] = sprintf($site['url'], $url);
        $options['verify'] = false;
        $res = HttpUtil::cfg_request_options($site, $options);
        $res = json_decode($res, true);
        if ($res['code'] == 200) {
            return $res['data'];
        } else {
            return false;
        }
    }

    /**
     * 拦截为false 正常为true
     * @param $grc
     * @param $result
     * @return array
     */
    private function _makeResult($grc, $result)
    {
        switch ($grc) {
            case "tencent_security":
                if ($result['state'] == 2) {
                    return [false, "{$result['result']}|{$result['reason']}"];
                }
                break;
            case '360_security':
            case 'google_security':
            case "wechat_security":
                if ($result['state'] == 1) {
                    return [false, "{$result['result']}"];
                }
                break;
            case 'douyin_security':
                if (in_array($result['state'], [1, 2])) {
                    return [false, "{$result['result']}|{$result['reason']}"];
                }
                break;
            case 'xiaomi_security':
                if ($result['state'] == 2) {
                    return [false, "{$result['result']}"];
                }
                break;
            case 'huawei_security':
                if ($result['state'] == 1) {
                    return [false, "{$result['result']}|{$result['reason']}"];
                }
                break;
            default:
                break;
        }
        return [true, "{$result['result']}"];
    }
}